(function() {
  'use strict';

  riot.tag('todo', document.getElementById('todo').innerHTML, function(opts) {
    var _this = this;
    var todos = _this.todos = opts.data || [];
    var filters = _this.filters = [
      'all',
      'active',
      'completed'
    ];

    riot.route.exec(function(base, filter) {
      _this.filter = filter || filters[0];
    });

    _this.on('update', function() {
      _this.remaining = todos.filter(function(t) {
        return !t.completed;
      }).length;
      _this.save();
    });

    _this.save = function() {
      todoStorage.save(_this.todos);
    };

    _this.add = function(e) {
      if (e.which == 13) {
        var value = e.target.value && e.target.value.trim();
        if (!value) {
          return;
        }
        todos.push({
          title: value,
          completed: false
        });
        e.target.value = '';
      }
    };

    _this.remove = function(todo) {
      todos.splice(todos.indexOf(todo), 1);
    };

    _this.toggleAll = function(e) {
      todos.forEach(function(t) {
        t.completed = e.target.checked;
      })
      return true;
    };

    _this.removeCompleted = function(e) {
      todos = _this.todos = todos.filter(function(t) {
        return !t.completed;
      });
    };

    riot.route(function(base, filter) {
      _this.filter = filter;
      _this.update();
    });
  });
}());
